<%@ Page Culture="en-US" UICulture="en-US" Language="C#" Explicit="true" Debug="true"%>

<%@ OutputCache Location="None" VaryByParam="None" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@Import Namespace="System.Globalization"%>
<%@Import Namespace="System.Threading"%>



<Script LANGUAGE="C#" runat="server">

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // To convert the SQL Server versions to MS Access do the following:-
  //   Replace the 2 DSN lines
  //   Replace all code of:-   SQLCommand   to   OleDbCommand
  //   Replace all code of:-   SQLDatareader   to   OleDbDatareader
  //   Replace Dates from '  to #  (do not need ' for SQL Server)  (eg strStartDate = "#" & strStartDate & "#")
  //   Change Function DateConvitfromformUS, also  (see comments in Function itself)
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

string strPK_ID;
string strPK_IDNEW;
string strarraysearch;
string strmachsearch;
string strSortField;
string strDispPageCounts;
long intRowIDGet;
long intPageIDGet;
long intSkipGet;
long intPageSizeGet;
string strPageload;
string strErrMsg;
string strmachtosave;
string strarraytosave;
string strstartdatetosave;
string strenddatetosave;
string strnotetosave;
string blnchktosave;
string strAction;
string strGUIDkey;
string strmachchanged;
string strarraychanged;
string strsdatechanged;
string strReinitialise;
bool blPageValid;


  //NET 1.1
  SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
  //NET 2.0
  //SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["DSN"]);
        
    //=======================================================================================
    // NOTE:-
    //Code that can be Customised are marked by &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    //
    //=======================================================================================


    void Page_Load() 
    {
                strAction = Request.QueryString["action"];

                //strPK_ID = Convert.ToString(Request.QueryString["num"]);     //passed PK_ID key (NOT NEEDED)
              
                //also get passed skipcount, pageid, rowid
                intRowIDGet = Convert.ToInt64(Request.QueryString["rowid"]);
                intPageIDGet = Convert.ToInt64(Request.QueryString["pageid"]);
                intSkipGet = Convert.ToInt64(Request.QueryString["skip"]);

                //get Sorted by field and PageSize, that are passed as well
                strSortField = Request.QueryString["sortby"];
                intPageSizeGet = Convert.ToInt64(Request.QueryString["pagesize"]);

              
                //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
                //Please change fields to be updated
                //------------------------------------------
                strmachtosave = Request.QueryString["machtosave"];
                strarraytosave = Request.QueryString["arraytosave"];
                strstartdatetosave = Request.QueryString["startdatetosave"];
                strenddatetosave = Request.QueryString["enddatetosave"];
                strnotetosave = Request.QueryString["notetosave"];
                blnchktosave = Request.QueryString["chktosave"];
                //END Fields to be Updated
                //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


                //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
                //Next Sort and Search fields are for if using LIST in conjunction (Do not need for Standalone Update form)
                //----------------------------------------------------------------------------------------------------------
                strarraysearch = Request.QueryString["arraysearch"]; 
                strmachsearch = Request.QueryString["machsearch"];  
             
                //END Optional Fields               
                //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

                //Response.Write("strPK_ID is  " + strPK_ID + "<br>");

                UpdateDBase();
           

                if (blPageValid == false) 
                {
                     Response.Write(strErrMsg);
                     Response.End();
                }
                else
                {
                  if (strAction == "byitself")           //DO not refresh LIST (if used)
                  {
                      Response.Write("");      //pass back nothing
                      Response.End();
                  }
                  else
                  { 
                    //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
                    //the next line is used also to check if Sort and Search Criteria fields have been changed (ie strReinitialise parameter)
                    //The next part is for using LIST in conjunction (Do not need for Standalone Update form)
                   Response.Redirect("ajax_kgrid_list.aspx?action=GetCurrentPage" 
                                  +  "&num=" + Server.UrlEncode(strGUIDkey) 
                                  +  "&rowid=" + Server.UrlEncode(Convert.ToString(intRowIDGet))
                                  +  "&skip=" + Server.UrlEncode(Convert.ToString(intSkipGet)) 
                                  +  "&sortby=" + Server.UrlEncode(strSortField) 
                                  +  "&textsearch=" + Server.UrlEncode(strarraysearch) 
                                  +  "&dropdownsearch=" + Server.UrlEncode(strmachsearch)  
                                  +  "&pageid=" + Server.UrlEncode(Convert.ToString(intPageIDGet)));

                   }       //strAction = "byitself"

                }

    }



    void GetSkipCount() 
    {
    //--------------------------------------------------------------------------------------------------------------------
    // PURPOSE SUMMARY:- Re-calculate PageID, RowID and SkipCount (if search or sort fields changed)
    //                                       So as to display in List correctly.
    //
    // PSEUDO CODE:-  Select PK_ID from Array table using unique Sortedby key
    //                              Read all records until PK_ID of record on page matches
    //                               when match found exit out read immediately
    //                               Re-calculate PageID, RowID and SkipCount, using derived RecordCount & PageSize
    //---------------------------------------------------------------------------------------------------------------------
        long intresult;
        long intremainder;
        long intRecordCount;
        int strwherecounter;
        string strSQLit;
        string strnotfound;
        SqlCommand objCmd;
        SqlDataReader objRdr;
        strwherecounter = 0;

        //Response.Write("PKID is " + strPK_ID + "<br>" );

         //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
         //Change as required
         strSQLit = "SELECT PK_ID FROM ARRAYS2 ";                             //customise to your Table
         strSQLit = strSQLit + " ORDER BY " + strSortField;                    //customise to your Table
         //strSQLit = strSQLit + " ORDER BY PK_ID";                             //customise to your Table
         //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

         //Response.Write("strSQLit is " + strSQLit + "<br>");

         objCmd = new SqlCommand(strSQLit, objConn);
         objConn.Open();
         objRdr = objCmd.ExecuteReader();

         intRecordCount = 0;
         strnotfound = "Yes";
         while (objRdr.Read())
         {
          intRecordCount = intRecordCount + 1;                                  //&&&&&&&&&&&&&&&&&&&&&&&&&&
          if (Convert.ToString(objRdr["PK_ID"]) == strGUIDkey)            //customise to the key in your Table
          {
            strnotfound = "No";
            break;
          }
         }

         objRdr.Close();
         objConn.Close();

        intresult = intRecordCount / intPageSizeGet;
        intremainder = intRecordCount % intPageSizeGet;

       //Response.Write("intresult  is " + intresult  + "<br>" );

        if (intremainder == 0) 
        {
          intRowIDGet = (intPageSizeGet - 1);                                 //must always take 1 off pageid (ie because row 1 is now row 0, for AJAX grid list)
          if (intRowIDGet < 0)                                //check tha rowid is not < 0
          {
            intRowIDGet = 0;
          }
          intPageIDGet = intresult;
          intSkipGet = (intresult * intPageSizeGet) - intPageSizeGet;
        }

        if (intremainder > 0) 
        {
          intRowIDGet = (intremainder - 1);                                      //must always take 1 off pageid (ie because row 1 is now row 0, for AJAX grid list)
          if (intRowIDGet < 0)                              //check tha rowid is not < 0
          {
            intRowIDGet = 0;
          }
          intPageIDGet = intresult + 1;
          intSkipGet = ((intresult + 1) * intPageSizeGet) - intPageSizeGet;
        }

    }



    //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    //Change as required
    //------------------------------------------------
    void UpdateDBase() 
    {
        string strSql;
        string strStartDate;
        string strEndDate;
        string blnCheck1;
        string strRecalculate;
        DateTime datSelected;
        string strnote;
        SqlCommand objCmd;
        SqlTransaction objTran;
        DateTime ws_conv_date;


     blPageValid = true;
     Session.LCID=2057;  //3081-AUS 1033-US 2057-BRITISH
     strStartDate = "";
     strEndDate = "";

      if (strmachtosave == null
                    || (strmachtosave.Length == 0)) 
      {
            strErrMsg = "Error - Machine is required!";
            blPageValid = false;
      }

      if ((strarraytosave == null) || (strarraytosave.Length == 0)) 
      {
            strErrMsg = "Error - Array is required!";
            blPageValid = false;
      }


      if (strstartdatetosave == null
                    || (strstartdatetosave.Length == 0)) 
      {
        strStartDate = "NULL";
      }
      else
      {
       if (IsDate(strstartdatetosave))
       {
        //ok
       }
       else
       {
          strErrMsg = "Error - Invalid Start Date!";
          blPageValid = false;
       }
     }


      if (strenddatetosave == null
                    || (strenddatetosave.Length == 0)) 
      {
        strEndDate = "NULL";
      }
      else
      {
       if (IsDate(strenddatetosave))
       {
        //ok
       }
       else
       {
          strErrMsg = "Error - Invalid End Date!";
          blPageValid = false;
       }
     }


     //Example of a check for a character in a field string
      if (strarraytosave == null
                    || (strarraytosave.Length == 0)) 
      {
        //nothing
      }
      else
      {
            if (strarraytosave.IndexOf("@") == -1)   //0 means there is @ at the start of the string
            {
             //strErrMsg = "Error - Email has @ missing!";
             //blPageValid = false;
            }
      }


     if (blPageValid == true)
     {
           
            if (strStartDate == "NULL")
            {
                //nothing
            }
            else
            {
                ws_conv_date = DateTime.Parse(strstartdatetosave);
                strStartDate = DateConvitfromformUS(ws_conv_date);        //yyyymmdd isodate format  
                strStartDate = "" + strStartDate + "";
            }


            if (strEndDate == "NULL")
            {
                //nothing
            }
            else
            {
                ws_conv_date = DateTime.Parse(strenddatetosave);
                strEndDate = DateConvitfromformUS(ws_conv_date);        //yyyymmdd isodate format  
                strEndDate = "" + strEndDate + "";
            }

           strarraytosave = strarraytosave.Replace("'","''");    //so as to cope with any Apostrophes in text
           strnotetosave = strnotetosave.Replace("'","''");                             //so as to cope with any Apostrophes in text
         

            if (blnchktosave == "true")
            {
              blnCheck1 = "True";
            }
            else
            {
              blnCheck1 = "False";
            }

         
            //create GUID Unique value for Primary Key
            //strGUIDkey = System.Guid.NewGuid().ToString();
           
            //strSql = "INSERT INTO ARRAYS (PK_ID, ";
            strSql = "INSERT INTO ARRAYS2 (loaded_machine, ";
            strSql = strSql + "array_name, ";
            strSql = strSql + "start_date, ";
            strSql = strSql + "end_date, ";
            strSql = strSql + "COMPLETE_FLAG, ";
            strSql = strSql + "comment) ";
            strSql = strSql + "VALUES ";
            //strSql = strSql + "('" + strGUIDkey + "', ";
            strSql = strSql + "('" + strmachtosave + "', ";
            strSql = strSql + "'" + strarraytosave + "', ";
            strSql = strSql + " " + strStartDate + ", ";
            strSql = strSql + "NULL, ";
            strSql = strSql + "'" + blnCheck1 + "', ";
            strSql = strSql + "'" + strnotetosave + "')";
            strSql = strSql + " select SCOPE_IDENTITY()";

            objCmd = new SqlCommand(strSql, objConn);

            objConn.Open();
            //Setting up Transaction
            objTran = objConn.BeginTransaction();
            objCmd.Transaction = objTran;
            try
            { 
                //objCmd.ExecuteNonQuery();
                strGUIDkey = Convert.ToString(objCmd.ExecuteScalar());
                objTran.Commit();
            }
            catch
            {
                objTran.Rollback();
            }
            finally
            {
                objConn.Close();
            }

   
             //Response.Write("About to do recalculate SkipCount");
             //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
             //Can set sortby to Primary Key only if wanting quick response, but recommend leaving it out
             //NOTE:- For very large tables, use the next line of code always, as Subquery sometimes too long to run,
             //            in AJAX_LIST.aspx, if using a text field as a Sort (seems OK for Date fields ie do not use next line).    
             //strSortField  = "PK_ID"      'so as to find record faster
             //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
             strmachsearch = "";
             strarraysearch = "";
             GetSkipCount();
         

       }        //blPageValid = true

    }
    //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
   


    private bool IsNumeric(object value)
    {
     bool Result = false;

     try {
       long i = Convert.ToInt64(value);
       Result = true;
     }
      catch
     { 
       // Ignore errors 
     }
       return Result;
     }


    private bool IsDate(object value)
    {
     bool Result = false;

     try {
       DateTime datSelected = Convert.ToDateTime(value);
       Result = true;
     }
      catch
     { 
       // Ignore errors 
     }
       return Result;
     }


    string dateconv(DateTime wsDate) {
        // convert create_date to yyyymmdd and dd/mm/yyyy
        string ws_dayy;
        string ws_yearr;
        string ws_monthh;
        string ws_dayit;
        string wzz_date;
        string ws_result_dated;
        DateTime wss_date;
        //wzz_date = wsDate.ToString("d");

        ws_result_dated = wsDate.ToString("d");

       // Response.Write("This Page is  " + wsDate.ToString() + "<br>");

        //if ((wsDate == null)) {]
        if ((ws_result_dated == null)) {
            return " ";
            //dateconvit = " ";
        }
        else {
           //wss_date = wsDate;
           ws_dayy = Convert.ToString(wsDate.Day);
           //ws_dayy = wsDate.ToString();

            //ws_dayy = datepart("d", wsDate);
            ws_dayit = ws_dayy;
            // response.write("lendate is" & ws_dayit.Length)
            if ((ws_dayit.Length == 1)) {
                ws_dayy = (0 + ws_dayy);
            }
            ws_monthh = Convert.ToString(wsDate.Month);
            //ws_monthh = DatePart("m", wsDate);
            if ((ws_monthh.Length == 1)) {
                ws_monthh = (0 + ws_monthh);
            }
            ws_yearr = Convert.ToString(wsDate.Year);
            //ws_yearr = DatePart("yyyy", wsDate);

            return (ws_dayy + ("/"
                        + (ws_monthh + ("/" + ws_yearr))));


        }
     }


    string DateConvitfromformUS(DateTime wsDate) {
        string stryyyy;
        string strmm;
        string strdd;
        string ws_dateit;
        string ws_len;
        string ws_find_delimiter;
        string ws_find_year;
        string strintermediate_result;
        string ws_result_dated;
        ws_result_dated = wsDate.ToString("d");

        strintermediate_result = "OK";

        if ((ws_result_dated == null)) {
            // DateConvitfromformUS = "NULL"
            strintermediate_result = "NULL";
        }
        else {
            // ===============================================
            // check if year is in yy or yyyy format
            // =============================================== 
            ws_len = Convert.ToString(ws_result_dated.Length);
            ws_find_delimiter = Convert.ToString((ws_result_dated.IndexOf("/", 3) + 1));
            if ((Convert.ToInt32(ws_find_delimiter) > 0)) {
                // OK found delimiter
            }
            else {
                ws_find_delimiter = Convert.ToString((ws_result_dated.IndexOf("-", 3) + 1));
            }
            if ((Convert.ToInt32(ws_find_delimiter) > 0)) {
                ws_find_year = ws_result_dated.Substring(((Convert.ToInt32(ws_find_delimiter) + 1) - 1), (Convert.ToInt32(ws_len) - Convert.ToInt32(ws_find_delimiter)));
                if ((ws_find_year.Length < 4)) {
                    // year is yy format
                    if ((ws_find_year.Length == 1)) {
                        ws_find_year = ("0" + ws_find_year);
                    }
                    if ((ws_find_year.Length == 3)) {
                        ws_find_year = ws_find_year.Substring(1, 2);
                    }
                    if ((Convert.ToInt32(ws_find_year) < 30)) {
                        // assume 2000 century if year less than 30
                        ws_find_year = ("20" + ws_find_year);
                    }
                    else {
                        ws_find_year = ("19" + ws_find_year);
                    }
                    ws_dateit = (ws_result_dated.Substring(0, Convert.ToInt32(ws_find_delimiter)) + Convert.ToInt32(ws_find_year));
                }
            }
            else {
                // DateConvitfromformUS = "NULL"
                strintermediate_result = "NULL";
            }
            // =================================================
            // End year check
            // =================================================
            // If DateConvitfromformUS = "NULL" Then
            if ((strintermediate_result == "NULL")) {
                // do nothing
            }
            else {
                stryyyy = Convert.ToString(wsDate.Year);
                //Response.Write("stryyyy  " + stryyyy  + "<br>");
                //stryyyy = DatePart("yyyy", wsDate);
                strmm = Convert.ToString(wsDate.Month);
                //strmm = DatePart("m", wsDate);
                if ((strmm.Length == 1)) {
                    strmm = (0 + strmm);
                }
                strdd = Convert.ToString(wsDate.Day);
                //strdd = DatePart("d", wsDate);
                if ((strdd.Length == 1)) {
                    strdd = (0 + strdd);
                }
                //Response.Write("strdd  " + strdd  + "<br>");
                //Response.Write("strmm  " + strmm  + "<br>");

                //Next 10 lines are MS Access code only
                //if ((Convert.ToInt32(strdd) > 12)) {
                    // will force what it thinks is a Month, a DAY
                  //  ws_dateit = (strdd + ("/" 
                    //            + (strmm + ("/" + stryyyy))));
                    // now US Format
                //}
                //else {
                  //  ws_dateit = (strmm + ("/" 
                    //            + (strdd + ("/" + stryyyy))));
                    // now US Format
                //}
           
                //Next line is SQL Server code only
                ws_dateit = ("cast(\'" + (stryyyy + (strmm + (strdd + "\' as DateTime)"))));

                strintermediate_result = ws_dateit;
            }
      
        }
        return strintermediate_result;
    }
  
  

</Script>


<HTML>
<HEAD>

</HEAD>
<BODY>

<form id="form1" method="post" runat="server">

</form>

</BODY>
</HTML>



